var mongoose = require('mongoose');
var mongoConf = require('config').get( 'mongo' );
var logger = require('./logger').logger();

if( process.env.MONGO_PWD ){
    Object.assign( mongoConf.opts, {pass: process.env.MONGO_PWD} );
}

if( global.Promise ){
    mongoose.Promise = global.Promise;
}

mongoose.connect( 
    mongoConf.uri, 
    mongoConf.opts 
);

var db = mongoose.connection;
db.on('error', function(err){
   logger.error( "mongoDB error:\t%j", err);
});
db.on('open', function() {
   logger.info( "mongoDB connected");
});

exports.db = db;
